<template>
  <div class="main-page list-page">
    <div
      class="content-box card-box"
      @click="handleClickPage"
      v-show="!showMore"
    >
      <el-card class="map">
        <template #header>
          <div class="card-box-header flex-box">
            <div>
              <el-button
                class="cus"
                type="primary"
                v-auth="`/projects/manage--add`"
                @click="handlerAdd"
                >创建新项目</el-button
              >
              <el-button
                class="cus"
                type="primary"
                v-auth="`/projects/manage--import`"
                @click="isDocument = true"
                >批量导入项目（B类）</el-button
              >
            </div>
            <div class="search-box">
              <el-date-picker
                v-model="formSearch.projectYear"
                type="year"
                format="YYYY年"
                value-format="YYYY"
                class="picker-box"
                style="width: 106px"
                @change="changeYear"
              />
              <template v-if="!showDeptList && !showDeptInput">
                <el-tooltip
                  class="box-item"
                  effect="light"
                  content="按区域/工厂查询项目"
                  placement="bottom"
                >
                  <p
                    class="icon-box"
                    @click.stop="
                      showDeptInput = true;
                      showDeptList = true;
                    "
                  >
                    <i class="icon snowfont icon-sousuo"></i>
                  </p>
                </el-tooltip>
              </template>
              <div class="tree-box" v-show="showDeptList || showDeptInput">
                <div class="input-wrap" v-show="showDeptInput">
                  <el-input
                    v-model.trim="filterText"
                    class="input-box"
                    placeholder="按区域/工厂查询项目"
                    clearable
                    @clear="clearTreeSearch"
                    @click.stop="showDeptList = true"
                  ></el-input>
                  <i class="icon snowfont icon-xiangmu"></i>
                </div>
                <el-tree
                  ref="treeRef"
                  class="filter-tree"
                  :data="deptList"
                  :props="defaultProps"
                  default-expand-all
                  :expand-on-click-node="false"
                  v-show="showDeptList"
                  :filter-node-method="filterNode"
                  @node-click="handleChangeDept"
                />
              </div>
            </div>
          </div>
        </template>
        <Map
          :dataList="mapData"
          @clickItem="clickMapItem"
          @cancleSelected="cancleSelectedMap"
          ref="mapRef"
        ></Map>
      </el-card>
      <el-card class="project">
        <template #header>
          <div class="h-top">
            <div class="total">
              <i class="snowfont icon-xiangmuliebiao"></i>
              <div class="list-text">
                <p>项目列表</p>
                <p class="num">
                  <span>{{ total }}</span>
                </p>
              </div>
            </div>
            <div>
              <el-input
                clearable
                class="list-input"
                placeholder="请输入项目名称搜索"
                v-model="formSearch.projectNameLike"
                @keyup.enter="handleSearch"
                @clear="handleSearch"
              />
              <el-select
                v-model="formSearch.projectTypeCode"
                value-key="dicCode"
                placeholder="请选择"
                class="list-type"
                @change="handleSearch"
                clearable
              >
                <el-option key="" label="全部" value=""></el-option>
                <el-option
                  class="default-option"
                  v-for="item in projectTypeList"
                  :label="item.dicValue"
                  :key="item.dicCode"
                  :value="item.dicCode"
                ></el-option>
              </el-select>
              <span class="exprand-box" @click="toggleShow">
                <i class="icon snowfont icon-zhankaicaidan"></i>
              </span>
              <!-- <el-button class="cus" @click.stop="handleReset">重置</el-button> -->
              <!-- <el-button class="cus" type="primary" @click="handleSearch"
                >查询</el-button
              > -->
            </div>
          </div>
        </template>

        <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
          <el-table
            :data="tableData"
            v-loading="loading"
            stripe
            :header-cell-style="{
              background: '#F7F9FD',
              color: '#000',
              height: '48px',
              borderTop: '1px soild #E4E8F2'
            }"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <el-table-column type="index" label="序号" width="50">
              <template v-slot="scope">
                <span>{{
                  (formSearch.pageNum - 1) * formSearch.pageSize +
                  scope.$index +
                  1
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="projectName"
              label="项目名称"
            ></el-table-column>
            <el-table-column
              label="项目类型"
              prop="projectTypeName"
              width="80"
            ></el-table-column>
            <el-table-column label="操作" width="90" fixed="right">
              <template #default="{ row }">
                <el-button
                  type="text"
                  v-auth="`/projects/manage--enter`"
                  @click="handleView(row)"
                  >进入</el-button
                >
                <el-button
                  class="delete"
                  type="text"
                  v-auth="`/projects/manage--delete`"
                  @click="showDeleteMessageBox(row)"
                  v-show="isShow || userId == row.projectLeaderId"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <re-pagination
            v-if="total > 0"
            :total="total"
            v-model:page="formSearch.pageNum"
            v-model:limit="formSearch.pageSize"
            @pagination="handleSearch(formSearch.pageNum)"
            class="constant-width"
            layout="prev, pager, next, jumper"
            :background="false"
          />
        </el-skeleton>
      </el-card>
    </div>
    <show-more-list
      v-show="showMore"
      :progressList="progressList"
      @toggleShow="toggleShow"
    ></show-more-list>
    <document-dom
      v-if="isDocument"
      ref="importRef"
      @cancel="isDocument = false"
      @submit="submitImport"
    ></document-dom>
  </div>
</template>

<script lang="ts">
import { reactive, ref, defineComponent, toRefs, watch, onMounted } from "vue";
import { useRouter } from "vue-router";
import RePagination from "/@/components/RePagination/index.vue";
import showMoreList from "./components/index.vue";
import documentDom from "./components/document.vue";
import { ElMessageBox } from "element-plus";
import { storageLocal } from "/@/utils/storage";
import {
  getDeptTreeByPro,
  projectManageList,
  importProject
} from "/@/api/projects";
import NotifMessage from "/@/utils/message/notification";
import Map from "/@/components/ReCharts/src/Map.vue";
import { ElTree } from "element-plus";
import { clickEvent } from "/@/utils/func";
import { postDictList } from "/@/api/home";
// import { postProjectAcceptbill } from "/@/api/analysis";
import { postProjectManageDelete } from "/@/api/project";
import { judgeRole } from "/@/api/project";
export default defineComponent({
  components: {
    RePagination,
    Map,
    showMoreList,
    documentDom
  },
  setup() {
    let router = useRouter();
    let formSearch = reactive({
      projectNameLike: "",
      projectRegionCode: "",
      projectFactoryCode: "",
      projectLeaderNameLike: "",
      projectTypeCode: "",
      projectYear: "",
      createTimeStrStart: "",
      createTimeStrEnd: "",
      pageNum: 1,
      pageSize: 10
    });
    //获取用户id
    let userId = ref("");
    if (storageLocal.getItem("info")) {
      userId.value = storageLocal.getItem("info")?.userId;
    }
    let tableData = ref([]);
    let loading = ref<boolean>(false);
    let total = ref<number>(0);
    let mapData = ref([]);
    let isShow = ref<boolean>();
    let mapRef = ref();
    let mapName = ref();
    let mapNameBrief = ref();
    const showMore = ref<boolean>(false);
    if (storageLocal.getItem("showMore")) {
      showMore.value = storageLocal.getItem("showMore");
    }
    const isDocument = ref<boolean>(false);
    const projectTypeList = ref([]);
    let state = reactive({
      defaultProps: {
        children: "children",
        label: "deptDescShrt"
      },
      showDeptList: false,
      showDeptInput: false
    });
    const filterText = ref("");
    const treeRef = ref<InstanceType<typeof ElTree>>();
    const importRef = ref<HTMLFormElement | null>(null) as any;
    let deptList = ref([]);

    watch(filterText, val => {
      treeRef.value!.filter(val);
    });

    const filterNode = (value: string, data) => {
      if (!value) return true;
      return data.deptDescShrt.includes(value);
    };

    onMounted(() => {
      getSelectData();
    });

    // 获取实施进度
    const progressList = ref([]);
    const getSelectData = async () => {
      try {
        const { data } = await postDictList({
          dicType: "project_progress_type"
        });
        progressList.value = data;
      } catch (error) {
        console.log(error);
      }
    };

    // 处理名称问题：将某某区域公司、某某区域转换为某某省
    const handleName = name => {
      let index = name.indexOf("区域");
      if (name.indexOf("华润雪花啤酒总部") > -1) {
        name = "北京市";
      } else if (index > 0) {
        name = name.slice(0, index) + "省";
      }
      return name;
    };

    const clearTree = () => {
      state.showDeptList = false;
      state.showDeptInput = false;
      let name = mapName.value;
      let newName = handleName(name);
      handleMapUnSelect(newName);
      filterText.value = "";
      formSearch.projectRegionCode = "";
      formSearch.projectFactoryCode = "";
      mapName.value = "";
    };

    const clearTreeSearch = () => {
      clearTree();
      getTableData();
    };

    const handleMapUnSelect = name => {
      mapRef.value.setMapUnSelect(name);
    };

    const handleClickPage = () => {
      if (!filterText.value) {
        state.showDeptList = false;
      }
      if (!formSearch.projectRegionCode && !formSearch.projectFactoryCode) {
        state.showDeptList = false;
        state.showDeptInput = false;
      }
    };

    // 选中树节点：3级子节点传至projectFactoryCode, 其他父节点传至projectRegionCode
    const handleChangeDept = (node, nodeObj) => {
      state.showDeptInput = true; // 显示输入框, 收起下拉列表
      state.showDeptList = false;
      let name = node.deptDescShrt;
      filterText.value = name;
      mapName.value = name; // 暂存，用于取消区域
      formSearch.projectFactoryCode = "";
      formSearch.projectRegionCode = "";
      if (nodeObj.isLeaf && nodeObj.level == 3) {
        formSearch.projectFactoryCode = node.id;
        formSearch.projectRegionCode = "";
        if (node.parentOrgId === "CR0121000002") {
          // 父id是华润雪花啤酒总部
          name = "华润雪花啤酒总部";
        }
      } else if (!node.parentOrgId) {
        // 根节点传空
        formSearch.projectRegionCode = "";
      } else {
        formSearch.projectRegionCode = node.id;
      }
      // 设置地图选中该区域
      let newName = handleName(name);
      mapRef.value.setMapSelect(newName);
      getTableData();
    };

    // 工厂区域
    const getDeptTreeFunc = async () => {
      try {
        const { data } = await getDeptTreeByPro({
          projectFactoryCode: formSearch.projectFactoryCode,
          projectRegionCode: formSearch.projectRegionCode,
          projectNameLike: formSearch.projectNameLike,
          projectYear: formSearch.projectYear
        });
        deptList.value = data || [];
        let mapDataList = [];
        let list = (deptList.value[0] && deptList.value[0].children) || [];
        list.forEach(item => {
          let name = item.deptDescShrt;
          name = handleName(name);
          let obj = {
            name,
            id: item.id,
            value: item.regionProCount
          };
          mapDataList.push(obj);
        });
        mapData.value = [...mapDataList];
      } catch (err) {
        console.log(err);
      }
    };

    const getTableData = async (updateTree?: boolean) => {
      updateTree && getDeptTreeFunc(); // 更新树的数据
      const { code, data } = await projectManageList({ ...formSearch });

      if (code === 200) {
        tableData.value = data.list;
        total.value = data.rows;
      }
    };

    // 项目类型
    const initProjectTypeList = async () => {
      try {
        const { data } = await postDictList({ dicType: "thd_pro_type" });
        projectTypeList.value = data || [];
      } catch (err) {
        console.log(err);
      }
    };

    getTableData(true);
    initProjectTypeList();

    const handlerAdd = (): void => {
      router.push("/projects/manage/space/add");
    };

    const handleView = row => {
      ["A", "B"].includes(row.projectTypeCode)
        ? router.push(`/projects${row.projectTypeCode}`)
        : row.projectTypeCode == "S"
        ? router.push(`/projectsB/manage/archives`)
        : router.push(`/projectsA`);
      storageLocal.removeItem("sectionInfo");
      storageLocal.setItem("projectInfo", {
        id: row.id,
        name: row.projectName,
        typeCode: row.projectTypeCode,
        typeName: row.projectTypeName,
        leaderId: row.projectLeaderId,
        leaderName: row.projectLeaderName,
        ...row
      });
    };

    const handleSearch = (page?: any) => {
      if (!page) {
        formSearch.pageNum = 1;
      }
      getTableData();
    };

    const filterChange = () => {
      handleSearch();
    };

    const changeYear = () => {
      if (formSearch.projectRegionCode === "9999") {
        formSearch.projectRegionCode = "";
        mapRef.value.setMapUnSelect(mapNameBrief.value);
      }
      getTableData(true);
    };

    const handleReset = () => {
      // formSearch.projectNameLike = "";
      // formSearch.projectYear = String(new Date().getFullYear());
    };

    const clickMapItem = (data, name) => {
      formSearch.projectRegionCode = (data && data.id) || "9999";
      formSearch.projectFactoryCode = "";
      filterText.value = "";
      mapNameBrief.value = name;
      getTableData();
    };

    const cancleSelectedMap = name => {
      if (name) {
        formSearch.projectRegionCode = "";
        mapNameBrief.value = "";
        getTableData();
      }
    };

    const toggleShow = () => {
      showMore.value = !showMore.value;
      storageLocal.setItem("showMore", showMore.value);
    };

    const submitImport = async formData => {
      try {
        const { code, message } = await importProject(formData);
        if (code === 200) {
          NotifMessage.success(message);
          clickEvent(
            "项目空间",
            "导入项目",
            `导入${formData.projectTypeCode}类项目`
          );
          isDocument.value = false;
          handleSearch();
        } else {
          NotifMessage.error(message || "请重试");
        }
      } catch (err) {
        importRef.value.handleRemove();
      }
    };

    //判断是否为超管，1是超管，0不是超管
    const deleteJudgeRole = async () => {
      try {
        const { data } = await judgeRole();
        if (data == 1) {
          isShow.value = true;
        } else {
          isShow.value = false;
        }
      } catch (err) {
        console.log(err);
      }
    };
    deleteJudgeRole();

    const showDeleteMessageBox = row => {
      ElMessageBox.confirm("确认删除该项目吗？", "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        iconClass: "el-icon-warning"
      })
        .then(() => {
          handleDelete(row);
        })
        .catch(() => {});
    };

    const handleDelete = async row => {
      try {
        const { code, message } = await postProjectManageDelete({ id: row.id });
        if (code === 200) {
          NotifMessage.success(message);
          getTableData();
        } else {
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    return {
      ...toRefs(state),
      formSearch,
      tableData,
      loading,
      total,
      treeRef,
      deptList,
      filterText,
      mapData,
      mapRef,
      projectTypeList,
      clearTreeSearch,
      handleClickPage,
      handleChangeDept,
      filterNode,
      handlerAdd,
      handleView,
      handleSearch,
      filterChange,
      changeYear,
      handleReset,
      clickMapItem,
      cancleSelectedMap,
      showMore,
      toggleShow,
      isDocument,
      submitImport,
      importRef,
      showDeleteMessageBox,
      userId,
      isShow,
      deleteJudgeRole,
      progressList
    };
  }
});
</script>

<style lang="scss" scoped>
.main-page {
  position: relative;
  width: 100%;
  height: 100%;
  .add {
    position: absolute;
    top: 20px;
    left: 20px;
  }
  .content-box {
    display: flex;
    flex-direction: row;
    min-height: 100%;
    .map {
      flex: 1;
      margin-right: 4px;
      min-width: 534px;
      .flex-box {
        display: flex;
        justify-content: space-between;
        .search-box {
          display: flex;
        }
      }
      .icon-box {
        width: 32px;
        height: 32px;
        background: #5298ff;
        border-radius: 4px;
        text-align: center;
        line-height: 32px;
        cursor: pointer;
        margin-left: 8px;
        i {
          font-size: 20px;
          color: #fff;
          font-weight: normal;
        }
      }
    }
    .project {
      width: 560px;
      min-width: 525px;
      overflow: auto;
      .h-top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        // margin-bottom: 20px;
        height: 32px;
        .total {
          display: flex;
          align-items: center;
          color: #495164;
          font-weight: bold;
          margin-right: 8px;
          i {
            font-weight: normal;
            font-size: 20px;
            color: #c2cade;
            margin-right: 10px;
          }
          .list-text {
            display: flex;
            align-items: center;
            p {
              font-size: 14px;
            }
          }
          .num {
            max-width: 70px;
            display: inline-block;
            border-radius: 4px;
            color: #5298ff;
            background: rgba(82, 152, 255, 0.1);
            font-size: 12px;
            margin-left: 6px;
            font-weight: bold;
            transform: skew(-20deg);
            margin-top: 2px;
            overflow: hidden;
            & > span {
              display: inline-block;
              transform: skew(20deg);
              width: 100%;
              padding: 2px 8px;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
              vertical-align: middle;
            }
          }
        }
      }
      .list-input {
        width: 212px;
        margin-right: 8px;
      }

      .list-type {
        width: 90px;
        margin-right: 8px;
      }
      .exprand-box {
        display: inline-block;
        width: 32px;
        height: 32px;
        background: rgba(82, 152, 255, 0.1);
        border-radius: 4px;
        line-height: 32px;
        text-align: center;
        cursor: pointer;
        vertical-align: middle;
        i {
          color: #5298ff;
          font-size: 20px;
        }
      }
    }
    .constant-width:deep .el-pagination {
      max-width: 560px;
      overflow: auto;
    }
  }
}
.tree-box {
  position: relative;
  width: 280px;
  // transition: width 0.2s;
  // &.show {
  //   width: 280px;
  // }
  .input-wrap {
    display: flex;
    align-items: center;
    width: 100%;
    padding-left: 8px;
    padding-right: 6px;
    // box-shadow: 0px 10px 10px 0px rgba(136, 149, 183, 0.3);
    background-color: #f7f9fd;
    i {
      font-size: 20px;
      color: #c2cade;
      margin-left: 4px;
    }
  }
  &:deep {
    .input-box {
      width: 242px;
      .el-input__inner {
        height: 24px;
        line-height: 24px;
        font-size: 12px;
        border: 1px solid #e4e8f2;
        padding: 4px 8px;
      }
    }
  }
}
.map {
  height: calc(100vh - 136px);
  &:deep {
    .el-card__body {
      padding: 0;
    }
  }
}
.filter-tree:deep {
  &.el-tree {
    position: absolute;
    top: 32px;
    right: 0;
    width: 280px;
    max-height: 552px;
    overflow-x: auto;
    overflow-y: auto;
    box-shadow: 0px 10px 10px 0px rgba(136, 149, 183, 0.3);
    z-index: 10;
    font-weight: normal;
    font-size: 12px;
    .el-tree-node > .el-tree-node__children {
      overflow: visible;
    }
  }
}
.delete {
  color: #e45d5d;
}
</style>
